/**
 * 
 */
package com.feib.stms.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import org.apache.commons.lang.StringUtils;

import com.feib.stms.model.LabelValue;
import com.feib.stms.model.MenuItem;
import com.feib.stms.model.Role;
import com.feib.stms.model.User;
import com.feib.stms.security.web.access.intercept.StmsFilterInvocationSecurityMetadataSource;
import com.feib.stms.service.MenuItemService;
import com.feib.stms.service.RoleService;
import com.feib.stms.util.MenuLoader;
import com.feib.stms.util.UserUtil;

/**
* @title (#)Stms9005ActionBean.java<br>
 * @description 角色設定 <br>
 * @author Karl Chen<br>
 * @version 1.0.0 2012/05/28
 * @2012/05/28 create by Karl Chen<br>
 *
 */
public class Stms9005ActionBean extends BaseActionBean 
{
	private static final long serialVersionUID = 5118831461890418399L;

	private static final String DEFAULT_JSP = "/WEB-INF/views/stms9005/stms9005.jsp";
    
	/**
     * 查詢條件--角色編號
     */
    private String rolePk;
    
    /**
     * 角色編號
     */
    private String roleNo;
    
    /**
     * 角色名稱
     */
    private String roleName;
    
    /**
     * 備註
     */
    private String roleNote;
    
    /**	
     * 功能選單
     */
    @SpringBean("menuLoader")
    private MenuLoader menuLoader;
    
    /**
     * 查詢結果-角色Object
     */
    private Role role;

    /**
     * 鈎選的子程式清單
     */
    private List<String> selectedActionBeans;
    
    /**
     * 修改的子程式選單
     */
    private String qryActionBeans;
    
    /**
     * 已被選擇的用戶
     */
    private List<LabelValue> selectedUser;
    
    /**
     * 未被選擇的用戶
     */
    private List<LabelValue> unSelectedUser;
    
    /**
     * 修改用--已被選擇的用戶
     */
    private String selectedUserForUpdate;
    
    /**
     * 新增狀態
     */
    private Boolean isAddStatus;
    
    /**
     * 執行結果信息
     */
    private String message;
    
    @SpringBean("roleService")
    private RoleService roleService;
    
    @SpringBean("menuItemService")
    private MenuItemService menuItemService;
    
    @SpringBean("stmsSecurityMetadataSource")
    private StmsFilterInvocationSecurityMetadataSource stmsFilterInvocationSecurityMetadataSource;
    
    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 查詢
     * @return
     */
    public Resolution doQuery()
    {
        logger.debug("Enter doQuery mehtod.");
        //封裝查詢條件
        Role role = new Role();
        
        //角色代碼
        role.setRoleNo(this.rolePk);
        
        /* 查詢角色名稱，角色編號，角色備註 */
        try {
        	this.role = roleService.getByRolePk(this.rolePk);
		} catch (Exception e) {
			this.role = null;
		}
        if (null == this.role){
        	this.message = "查無資料！";
        	return new ForwardResolution(DEFAULT_JSP); 
        }else{
        	this.roleNo = this.role.getRoleNo();
        	this.roleName = this.role.getRoleName();
        	this.roleNote = this.role.getRoleNote();
        }
        
        /* 查詢功能用戶的菜單權限,效能可以改善 */
        try {
        	this.selectedActionBeans = roleService.getMenuItemPkByRoleId(this.rolePk);
		} catch (Exception e) {
			this.selectedActionBeans = null;
		}
        
        /* 查詢該角色權限下的用戶 */
        //如果資料清空
        this.selectedUser = new ArrayList<LabelValue>();        

    	//保存查詢到得用戶
    	List<User> tempUser;
    	//獲取當前登錄用戶的GroupPk
    	Long userGroupPk = UserUtil.getUserGroup().getGroupPk();
    	//去數據庫查詢資料
    	try{
    		tempUser = roleService.findAllSelectedRoleUserByGroupPk(this.rolePk, userGroupPk);
    	} catch (Exception e) {
			tempUser = null;
		}
    	//轉化資料為可用數據
    	if(null != tempUser && tempUser.size() > 0){
    		LabelValue labelValue;
    		for(int i = 0 ; i < tempUser.size() ; i++){
    			labelValue = new LabelValue();
    			//頁面僅顯示為用戶ID
    			labelValue.setLabel(tempUser.get(i).getUserId());
    			labelValue.setValue(tempUser.get(i).getUserPk().toString());
    			this.selectedUser.add(labelValue);
    		}
    	}
        
        /* 查詢所有未擁有此權限的用戶 */
        this.unSelectedUser = new ArrayList<LabelValue>();
    	//保存查詢到得用戶
    	List<User> tempUser1;
    	//獲取當前登錄用戶的GroupPk
    	Long userGroupPk1 = UserUtil.getUserGroup().getGroupPk();
    	//去數據庫查詢資料
    	try{
    		tempUser1 = roleService.findAllUnSelectedRoleUserByGroupPk(this.rolePk, userGroupPk1);
    	} catch (Exception e) {
			tempUser1 = null;
		}
    	//轉化資料為可用數據
    	if(null != tempUser1 && tempUser1.size() > 0){
    		LabelValue labelValue;
    		for(int i = 0 ; i < tempUser1.size() ; i++){
    			labelValue = new LabelValue();
    			//頁面僅顯示為用戶ID
    			labelValue.setLabel(tempUser1.get(i).getUserId());
    			labelValue.setValue(tempUser1.get(i).getUserPk().toString());
    			this.unSelectedUser.add(labelValue);
    		}
    	}
        
        return new ForwardResolution(DEFAULT_JSP); 
    }

    /**
     * 跳轉到新增
     * @return
     */
    public Resolution doInitCreate(){
    	logger.debug("Enter doInitCreate method.");
    	//新增狀態
    	this.isAddStatus = true;
    	//清空ROLE
    	this.rolePk = null;
    	this.roleName = null;
    	this.roleNo = null;
    	this.roleNote = null;
    	this.role = null;
    	
    	this.selectedActionBeans = new ArrayList<String>();
    	this.selectedActionBeans.add("-1");
    	

        /* 可選角色 */
    	this.selectedUser = null;
    	this.unSelectedUser = new ArrayList<LabelValue>();
    	Long userGroupPk = UserUtil.getUserGroup().getGroupPk();
    	List<User> tempUser = roleService.findAllUnSelectedRoleUserByGroupPk("0", userGroupPk);
    	//轉化資料為可用數據
    	if(null != tempUser && tempUser.size() > 0){
    		LabelValue labelValue;
    		for(int i = 0 ; i < tempUser.size() ; i++){
    			labelValue = new LabelValue();
    			//頁面僅顯示為用戶ID
    			labelValue.setLabel(tempUser.get(i).getUserId());
    			labelValue.setValue(tempUser.get(i).getUserPk().toString());
    			this.unSelectedUser.add(labelValue);
    		}
    	}
    	
    	return new ForwardResolution(DEFAULT_JSP);
    }
    
    /**
     * 新增
     * @return
     */
    public Resolution doCreate()
    {	
    	logger.debug("Enter doCreate mehtod.");
    	//獲取當前登錄用戶
    	User user = UserUtil.getUser();
    	//創建人
    	String createdUser = user.getGroup().getGroupNo()+"_"+user.getUserId();
    	role = new Role();
    	role.setCreatedBy(createdUser);
    	//ROLE信息
    	role.setRoleNo(this.roleNo);
    	role.setRoleName(this.roleName);
    	role.setRoleNote(this.roleNote);
    	role.setGroup(user.getGroup());
    	/* 創建MenuItem */
        //用戶現在選擇的MenuItem
        List<String> tempActionBeans = new ArrayList<String>();
        if(StringUtils.isNotEmpty(this.qryActionBeans)){        	            
            if (null != this.qryActionBeans)
            {
                String[] abs = this.qryActionBeans.split(",");
                for(String actionBean: abs)
                {
                    if (null != actionBean)
                    {
                    	tempActionBeans.add(actionBean);
                    }
                }
            }            
        }
        //創建Role User
        List<String> tempUser = new ArrayList<String>();
        if(StringUtils.isNotEmpty(this.selectedUserForUpdate)){
        	if (null != this.selectedUserForUpdate)
            {
                String[] abs = this.selectedUserForUpdate.split(",");
                for(String tempUserPk: abs)
                {
                    if (null != tempUserPk)
                    {
                    	tempUser.add(tempUserPk);
                    }
                }
            }
        }
    	boolean flag = this.roleService.insert(role, tempActionBeans, role.getRolePk(), tempUser);
    	message = flag?"新增成功！":"新增失敗!";
    	//更新 Spring Security 設定
        stmsFilterInvocationSecurityMetadataSource.setToReload();
    	this.isAddStatus = false;
    	this.role = null;
    	return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 更新
     * @return
     */
    public Resolution doUpdate()
    {
        logger.debug("Enter doUpdate mehtod.");
        //獲取當前登錄用戶
        User user = UserUtil.getUser();
        //拼接更新人員名冊
        String updateUser = user.getGroup().getGroupNo() + "_" + user.getUserId();
        //賦值Role的更新
        //從db中獲取Role
        Role roleFromDb = this.roleService.getByRolePk(rolePk);
        roleFromDb.setUpdatedBy(updateUser);
        roleFromDb.setRolePk(Long.valueOf(this.rolePk));
        roleFromDb.setRoleNo(this.roleNo);
        roleFromDb.setRoleName(this.roleName);
        roleFromDb.setRoleNote(this.roleNote);
        //1.更新Role
        
        /* 更新MenuItem */
        //用戶現在選擇的MenuItem
        List<String> tempActionBeans = new ArrayList<String>();
        if(StringUtils.isNotEmpty(this.qryActionBeans)){        	            
            if (null != this.qryActionBeans)
            {
                String[] abs = this.qryActionBeans.split(",");
                for(String actionBean: abs)
                {
                    if (null != actionBean)
                    {
                    	tempActionBeans.add(actionBean);
                    }
                }
            }            
        }
        
        //創建Role User
        List<String> tempUser = new ArrayList<String>();
        if(StringUtils.isNotEmpty(this.selectedUserForUpdate)){
        	if (null != this.selectedUserForUpdate)
            {
                String[] abs = this.selectedUserForUpdate.split(",");
                for(String tempUserPk: abs)
                {
                    if (null != tempUserPk)
                    {
                    	tempUser.add(tempUserPk);
                    }
                }
            }
        }
        boolean flag = this.roleService.update(roleFromDb, tempActionBeans, roleFromDb.getRolePk(), tempUser);
        message = flag?"更新成功!":"更新失敗!";
        //更新 Spring Security 設定
        stmsFilterInvocationSecurityMetadataSource.setToReload();
        return new ForwardResolution(DEFAULT_JSP);
    }

    /**
     * 匯出Excel檔案
     * @return
     */
    public Resolution doExportExcel()
    {
    	try {
    		
    		// TODO: 產生Excel
    		String downloadFilePath = "";
    		
    		File downloadFile = new File(downloadFilePath);
            byte[] bytes = new byte[(int)downloadFile.length()];
            
            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(downloadFile)); 

            bufferedInputStream.read(bytes);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            inputStream.close();
            bufferedInputStream.close();

            String isoFileName = new String("上傳記錄查詢結果.xls".getBytes("MS950"), "ISO8859-1");

            StreamingResolution streamingResolution = new StreamingResolution("application/vnd.ms-excel",inputStream).setFilename(isoFileName);

            return streamingResolution;
		} catch (Exception e) {
            logger.error("", e);
		}
        return new ForwardResolution(DEFAULT_JSP); 
    }
    
    /**
     * 下拉選單的獲取
     * @return
     */
    public List<LabelValue> getRoleNoList(){
    	/* 設置LIST來保存查詢到得數據 */
    	List<LabelValue> list = new ArrayList<LabelValue>();
    	/* 從數據庫獲取功能角色,并添加到頁面 */
    	String userGroupPk = UserUtil.getUserGroup().getGroupPk().toString();
        list = roleService.findLabelValueByGroupPk(userGroupPk);
    	return list;
    }
    
    /**
     * 返回功能名稱表
     * @return
     */
    public List<List> getFunctionsList() {
       	/* 總List */
    	List<List> sumList = new ArrayList<List>();
    	/* 某一程式群組及其下程式功能 */
    	List<LabelValue> tmpList = new ArrayList<LabelValue>();
    	
    	/* 動態獲取程式中菜單 */
    	List<MenuItem> menuItem = new ArrayList<MenuItem>();
    	/* 根據使用者的登入情況進行程式選單的判斷 */
    	if(UserUtil.isBankGroup()){
    		menuItem = menuLoader.getMenuItems();
    	}else{
    		menuItem = menuItemService.getAllEnabledMenuItemsForSecuritiesWithRoles();
    	}	
		
		/* 如果菜單不為空則導入菜單到List中 */
    	if(menuItem != null && menuItem.size() > 0){
    		int menuItemSize = menuItem.size();
    		
    		/* 獲取用戶選擇的查詢條件-功能名稱 */
            /* 循環添加功能名稱 */
    		for (int i = 0; i < menuItemSize; i++) {
    			/* 只有當數據庫中父菜單ID及ActionBeanClass為空才為父菜單 */
    			boolean isParentMenu = (menuItem.get(i).getParentMenuItem() == null || "".equals(menuItem.get(i).getParentMenuItem()))
    								&& (menuItem.get(i).getActionBeanClass() == null || "".equals(menuItem.get(i).getActionBeanClass()));
    			/* 如果是父菜單，則創建新的List來保存其及其下相關程式功能 */
				if(isParentMenu){
					/* 每次遇到不為空的父菜單，都把上一個List提交，并創建新的List */
					if(tmpList != null && tmpList.size() > 1){
						sumList.add(tmpList);
					}
					/* 當用戶已經選擇過功能名稱時，保存已經選擇的選項 */
					if(null != this.selectedActionBeans && this.selectedActionBeans.size() > 0){
						int actionBeansSize = this.selectedActionBeans.size();
						tmpList = new ArrayList<LabelValue>();
						LabelValue labelValue = new LabelValue();
    					labelValue.setLabel(menuItem.get(i).getActionName());
    					labelValue.setValue(menuItem.get(i).getMenuItemPk().toString());
    					boolean isEqual = false;
						for (int k = 0; k < actionBeansSize; k++) {
			    			String selectedItem = this.selectedActionBeans.get(k);
			    			isEqual = selectedItem.equals(menuItem.get(i).getMenuItemPk().toString());
			    			//當遇到匹配的情況，則保存選項，并跳出循環.
			    			if(isEqual){
			    				labelValue.setChecked(true);
			    				break;
			    			}
			    		}
						if(!isEqual){
							labelValue.setChecked(false);
						}
						tmpList.add(labelValue);
					}else{
						tmpList = new ArrayList<LabelValue>();
						LabelValue labelValue = new LabelValue();
						labelValue.setLabel(menuItem.get(i).getActionName());
						labelValue.setValue(menuItem.get(i).getMenuItemPk().toString());
						labelValue.setChecked(false);
						tmpList.add(labelValue);
					}
				}
				/* 子菜單的保存 */
				else {
					/*當用戶已經選擇過功能名稱時，保存已經選擇的選項 */
					if(null != this.selectedActionBeans && this.selectedActionBeans.size() > 0){
						int actionBeansSize = this.selectedActionBeans.size();						
						LabelValue labelValue = new LabelValue();
    					labelValue.setLabel(menuItem.get(i).getActionName());
    					labelValue.setValue(menuItem.get(i).getMenuItemPk().toString());
    					boolean isEqual = false;
						for (int k = 0; k < actionBeansSize; k++) {
			    			String selectedItem = this.selectedActionBeans.get(k);
			    			isEqual = selectedItem.equals(menuItem.get(i).getMenuItemPk().toString());
//			    			當遇到匹配的情況，則保存選項，并跳出循環.
			    			if(isEqual){
			    				labelValue.setChecked(true);
			    				break;
			    			}
			    		}
						if(!isEqual){
							labelValue.setChecked(false);
						}
						tmpList.add(labelValue);
					}else{
						LabelValue labelValue = new LabelValue();
						labelValue.setLabel(menuItem.get(i).getActionName());
						labelValue.setValue(menuItem.get(i).getMenuItemPk().toString());
						labelValue.setChecked(false);
						tmpList.add(labelValue);
					}				
					/* 提交最後一筆，當且僅當該程式為子菜單時 */
					if(i == menuItemSize - 1){
						sumList.add(tmpList);
					}
				}				
			}
    	}    	
    	return sumList;
    }
    
	/**
	 * @return message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message 的設定的 message
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * @return menuLoader
	 */
	public MenuLoader getMenuLoader() {
		return menuLoader;
	}

	/**
	 * @param menuLoader 的設定的 menuLoader
	 */
	public void setMenuLoader(MenuLoader menuLoader) {
		this.menuLoader = menuLoader;
	}

	/**
	 * @return selectedActionBeans
	 */
	public List<String> getSelectedActionBeans() {
		return selectedActionBeans;
	}

	/**
	 * @param selectedActionBeans 的設定的 selectedActionBeans
	 */
	public void setSelectedActionBeans(List<String> selectedActionBeans) {
		this.selectedActionBeans = selectedActionBeans;
	}

	/**
	 * @return role
	 */
	public Role getRole() {
		return role;
	}

	/**
	 * @param role 的設定的 role
	 */
	public void setRole(Role role) {
		this.role = role;
	}

	/**
	 * @return roleName
	 */
	public String getRoleName() {
		return roleName;
	}

	/**
	 * @param roleName 的設定的 roleName
	 */
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	/**
	 * @return roleNo
	 */
	public String getRoleNo() {
		return roleNo;
	}

	/**
	 * @param roleNo 的設定的 roleNo
	 */
	public void setRoleNo(String roleNo) {
		this.roleNo = roleNo;
	}

	/**
	 * @return roleNote
	 */
	public String getRoleNote() {
		return roleNote;
	}

	/**
	 * @param roleNote 的設定的 roleNote
	 */
	public void setRoleNote(String roleNote) {
		this.roleNote = roleNote;
	}

	/**
	 * @return selectedUser
	 */
	public List<LabelValue> getSelectedUser() {
		return selectedUser;
	}

	/**
	 * @param selectedUser 的設定的 selectedUser
	 */
	public void setSelectedUser(List<LabelValue> selectedUser) {
		this.selectedUser = selectedUser;
	}

	/**
	 * @return unSelectedUser
	 */
	public List<LabelValue> getUnSelectedUser() {
		return unSelectedUser;
	}

	/**
	 * @param unSelectedUser 的設定的 unSelectedUser
	 */
	public void setUnSelectedUser(List<LabelValue> unSelectedUser) {
		this.unSelectedUser = unSelectedUser;
	}

	/**
	 * @return rolePk
	 */
	public String getRolePk() {
		return rolePk;
	}

	/**
	 * @param rolePk 的設定的 rolePk
	 */
	public void setRolePk(String rolePk) {
		this.rolePk = rolePk;
	}

	/**
	 * @return qryActionBeans
	 */
	public String getQryActionBeans() {
		return qryActionBeans;
	}

	/**
	 * @param qryActionBeans 的設定的 qryActionBeans
	 */
	public void setQryActionBeans(String qryActionBeans) {
		this.qryActionBeans = qryActionBeans;
	}

	/**
	 * @return selectedUserForUpdate
	 */
	public String getSelectedUserForUpdate() {
		return selectedUserForUpdate;
	}

	/**
	 * @param selectedUserForUpdate 的設定的 selectedUserForUpdate
	 */
	public void setSelectedUserForUpdate(String selectedUserForUpdate) {
		this.selectedUserForUpdate = selectedUserForUpdate;
	}

	/**
	 * @return isAddStatus
	 */
	public Boolean getIsAddStatus() {
		return isAddStatus;
	}

	/**
	 * @param isAddStatus 的設定的 isAddStatus
	 */
	public void setIsAddStatus(Boolean isAddStatus) {
		this.isAddStatus = isAddStatus;
	}
}
